# -*- coding:utf-8 -*-
from com.zzh.utils.dbUtils import MysqlUtils
from com.zzh.utils.table2Json_v2 import Table2JsonByYM
from com.zzh.utils.pagingUtils import MyPaging
from com.zzh.utils.requestFieldMapDBField import requestFieldMapToDBField_YM
from com.zzh.utils.sqlUtils.SqlUtils import SqlUtils
import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

import time
from com.zzh.utils.pagingUtils import MyPaging
localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


class MessageAPI(object):
    def __init__(self):
        self.conn = MysqlUtils.get_mysql_connections_v2()

    def queryMessage(self, id):
        cur = self.conn.cursor()
        sql = "select * from zzh_message WHERE message_id=%s"
        total_count = cur.execute(sql, [id])
        if total_count:
            messageList = cur.fetchall()
            messageListJson = Table2JsonByYM.message_list_to_json(messageList)
            cur.close()
            self.conn.close()
            return total_count, messageListJson
        else:
            return 0 ,None

    def addMessage(self, message_info):
        messageType = message_info['messageType']
        postId = message_info['postId']
        postName = message_info['postName']
        acceptId = message_info['acceptId']
        acceptName = message_info['acceptName']
        messageIsRead = message_info['messageIsRead']
        messageTitle = message_info['messageTitle']
        messageContent = message_info['messageContent']
        messagePostTime = message_info['messagePostTime']
        messageReadTime = message_info['messageReadTime']

        sql = "INSERT into zzh_message (message_type,post_id,post_name,accept_id,accept_name,message_is_read,message_title,message_content,message_post_time,message_read_time) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        cur = self.conn.cursor()
        rs = cur.execute(sql, [messageType, postId, postName, acceptId, acceptName, messageIsRead, messageTitle, messageContent, messagePostTime, messageReadTime])
        self.conn.commit()
        cur.close()
        self.conn.close()
        return rs


    def selectMessage(self, id):
        """
        根据ID查询信息，返回元组

        """
        sql = "select * from zzh_message WHERE message_id=%s"

        cur = self.conn.cursor()
        rs = cur.execute(sql, [id])
        arr = cur.fetchone()
        cur.close()
        self.conn.close()
        return arr

    def updateMessageById(self, messageInfo):

        acceptId = str(messageInfo["acceptId"])
        messageReadTime = localTime
        isLock = str(messageInfo["isLock"])
        messageId = messageInfo["messageId"]
        messageIsRead = str(messageInfo["messageIsRead"])
        cur = self.conn.cursor()
        sql = "UPDATE zzh_message SET message_is_read=%s, message_read_time=%s, isLock=%s, accept_id=%s WHERE message_id=%s"

        for i in messageId:
            i = str(i)
            updateMessageResultOfDatabase = cur.execute(sql, [messageIsRead, messageReadTime, isLock, acceptId, i])
        self.conn.commit()
        
        if updateMessageResultOfDatabase:
            cur.close()
            self.conn.close()
            return 1
        else:
            cur.close()
            self.conn.close()
            return 0

    def deleteMessageById(self, messageId):
        cur = self.conn.cursor()
        sql = "DELETE from zzh_message WHERE message_id=%s"
        for id in messageId:
            deletePaymentResultOfDatabase = cur.execute(sql, [id])
        self.conn.commit()
        if deletePaymentResultOfDatabase:
            cur.close()
            self.conn.close()
            return 1
        else:
            cur.close()
            self.conn.close()
            return 0

    def queryMessageByCondition(self, **kwargs):

        conditions = kwargs['conditions']
        multiSort = kwargs['multiSort']
        pageIndex = kwargs['pageIndex']
        pageSize = kwargs['pageSize']


        fieldMap = requestFieldMapToDBField_YM.messageMap  # 要改的这个
        whereSentence = SqlUtils.getOption(conditions, fieldMap)

        cur = self.conn.cursor()

        if multiSort:
            # 排序拼接

            sortRule = SqlUtils.getSortRule(multiSort, fieldMap)
            sql = "SELECT * FROM zzh_message WHERE isLock=1 and " + whereSentence + " ORDER BY " + sortRule
        else:
            sql = "SELECT * FROM zzh_message WHERE isLock=1 and " + whereSentence

        total_count = cur.execute(sql)
        if total_count:
            result = cur.fetchall()
            cur.close()
            self.conn.close()
            resultList = MyPaging().getPage(total_count, pageIndex, pageSize, result)
            userOauthJSON = Table2JsonByYM.message_list_to_json(resultList)
            return userOauthJSON, total_count
        else:

            cur.close()
            self.conn.close()
            return None, 0
